package payrechargelogic

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/recharge"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/config"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/service"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type RechargeSuccessLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRechargeSuccessLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RechargeSuccessLogic {
	return &RechargeSuccessLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// RechargeSuccess 充值成功处理
func (l *RechargeSuccessLogic) RechargeSuccess(in *rpc.NotifyOKRequest) (*rpc.NotifyResponse, error) {
	// 获取未处理订单
	order, err := recharge.NewRechargeOrderModel(l.ctx, l.svcCtx.Db).GetInitOrder(in.OrderNo)
	if err != nil {
		return nil, err
	}

	err = l.svcCtx.Db.Transaction(func(tx *gorm.DB) error {
		// 开启事务

		// 修改订单状态【成功】
		err = recharge.NewRechargeOrderModel(l.ctx, tx).UpdateStatusSuccess(order.OrderNo, in.ReturnJson)
		if err != nil {
			return err
		}

		// 调用统一加减余额接口
		incrReq := &rpc.BalanceIncreaseRequest{
			UserId:   order.UserID,
			Amount:   order.Amount,
			TypeId:   config.TYPE_RECHARGE,
			SourceId: order.OrderNo,
			Code:     order.Coin,
		}
		if _, err = service.BalanceIncrease(l.ctx, l.svcCtx, incrReq, &rpc.Facebook{
			Ip:           order.Ip,
			UserAgent:    order.UserAgent,
			Fbc:          order.Fbc,
			Fbp:          order.Fbp,
			FacebookAdId: order.FacebookAdId,
			SiteUrl:      order.SiteUrl,
			Email:        order.Email,
			Telephone:    order.Telephone,
		}); err != nil {
			return err
		}

		// 提交事务
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &rpc.NotifyResponse{}, nil
}
